package com.achievement.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.achievement.entity.Course;
import com.achievement.entity.dto.CourseDTO;
import com.achievement.service.ICourseService;
import com.common.util.AjaxResponse;
import com.common.util.JpaPageable;
import com.common.util.TablePage;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("/course")
public class CourseController {
	@Autowired
	private ICourseService courseService;
	
	@RequestMapping("/saveOrUpdate")
	public @ResponseBody AjaxResponse saveOrUpdate(String course) {
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			Course obj = objectMapper.readValue(course,Course.class);
			if(courseService.isNumExist(obj))
				return new AjaxResponse(false, "编号已存在!");
			courseService.saveOrUpdate(obj);
			return new AjaxResponse(true, "操作成功!");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new AjaxResponse(false, "操作失败...");
		}
	}
	@RequestMapping("/findPage")
	public @ResponseBody TablePage<Course> findPage(JpaPageable pageable,String str,Long subject_id){
		try {
			return courseService.findPage(CourseDTO.getFindPageSpec(str, subject_id), pageable.getPageable());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	@RequestMapping("/findAll")
	public @ResponseBody List<Course> findAll(){
		try {
			return courseService.findAll();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	@RequestMapping("/findTest")
	public @ResponseBody List<Course> findATest(){
		try {
			return courseService.findTest();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	@RequestMapping("/delete")
	public @ResponseBody AjaxResponse delete(Long id) {
		try {
			if(courseService.hasExam(id))
				return new AjaxResponse(false, "课程有考试，不允许删除!");
			if(courseService.hasStudent(id))
				return new AjaxResponse(false, "已有学生选课，不能删除!");
			courseService.delete(id);
			return new AjaxResponse(true, "已删除!");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new AjaxResponse(false, "删除失败...");
		}
	}
}
